﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.Web;
using System.Web.UI;
using System.Xml;
using Microsoft.SharePoint;
using System.IO;
using System.Xml.Serialization;

namespace SharePoint.Intranet.AlertImportExport
{
    public class AlertImportExport : Page
    {


        protected Button btnExport;
        protected Button btnImport;
        protected InputFormCheckBox chkDeleteOnExport;
        protected InputFormCheckBox chkDeleteOnImport;
        protected FileUpload uplImportXml;
        protected Label lblSuccess;
        protected Label lblError;

        
        protected void Page_PreLoad()
        {
            if (Request.QueryString["export"] == "true")
            {
                XmlDocument xmlDoc = new XmlDocument();

                XmlNode parentNode = xmlDoc.CreateElement("Alerts");

                SPWeb web = SPContext.Current.Web;

                foreach (SPAlert alert in web.Alerts)
                {
                    AlertDetails alertDetails = new AlertDetails(alert);
                    if (!string.IsNullOrEmpty(alertDetails.AlertType))
                    {
                        XmlDocumentFragment output = xmlDoc.CreateDocumentFragment();
                        output.InnerXml = alertDetails.ToXml();
                        parentNode.AppendChild(output);
                    }
                }
                xmlDoc.AppendChild(parentNode);


                web.AllowUnsafeUpdates = true;
                if (bool.Parse(Request.QueryString["delete"]) == true)
                {
                    for (int i = 0; i < web.Alerts.Count; i++)
                    {
                        web.Alerts.Delete(0);
                    }
                }
                web.AllowUnsafeUpdates = false;

                Response.ContentType = "text/xml";
                Response.AppendHeader("content-disposition", string.Format("attachment; filename={0}_Alerts.xml", web.Title));
                xmlDoc.Save(Response.OutputStream);
                Response.End();
                
            }
            
        }


        protected void btnExport_Click(Object Sender, EventArgs e)
        {
            SPUtility.Redirect("AlertImportExport.aspx?export=true&delete=" + chkDeleteOnExport.Checked.ToString(), SPRedirectFlags.DoNotEncodeUrl, HttpContext.Current);
        }



        protected void btnImport_Click(Object Sender, EventArgs e)
        {
            if (uplImportXml.HasFile)
            {
                SPWeb web = SPContext.Current.Web;

                if (chkDeleteOnImport.Checked)
                {
                    for (int i = 0; i < web.Alerts.Count; i++)
                    {
                        web.Alerts.Delete(0);
                    }
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(uplImportXml.FileContent);


                XmlNodeList alertNodes = xmlDoc.SelectNodes("//Alerts/AlertDetails");

                if (alertNodes.Count > 0)
                {
                    foreach (XmlNode alertNode in alertNodes)
                    {
                        StringReader sr = new StringReader(alertNode.OuterXml);
                        XmlSerializer s = new XmlSerializer(typeof(AlertDetails));
                        AlertDetails newAlert = (AlertDetails)s.Deserialize(sr);

                        SPUser alertUser = web.SiteUsers.GetByID(newAlert.UserId);
                        SPAlert newSPAlert = alertUser.Alerts.Add();

                        if (newAlert.ListID != Guid.Empty)
                        {
                            newSPAlert.AlertType = SPAlertType.List;
                            newSPAlert.List = web.Lists[newAlert.ListID];
                            newSPAlert.EventType = (SPEventType)Enum.Parse(typeof(SPEventType), newAlert.EventType);
                            newSPAlert.AlertFrequency = (SPAlertFrequency)Enum.Parse(typeof(SPAlertFrequency), newAlert.AlertFrequency);
                            if (newAlert.AlertFrequency.ToLower() != "immediate")
                            {
                                newSPAlert.AlertTime = newAlert.AlertTime;
                            }
                            newSPAlert.Title = newAlert.Title;
                            newSPAlert.Update(false);
                        }

                        lblSuccess.Visible = true;
                    }
                }
                else
                {
                    lblError.Text = "There are no alerts in the XML file to import.";
                    lblError.Visible = true;
                }
                
            }
            else
            {
                lblError.Text = "Please upload an XML file to import alerts from";
                lblError.Visible = true;
            }
        }
    }
}
